﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;

namespace VideoSpider.Module.Request
{
    public class XJNetworkRequest
    {
        HttpWebRequest request = null;
        public int timeOut = 10000;
        public Encoding encoding = Encoding.UTF8;
        string method = null;
        string URL = null;
        public RequestDelegate requestDelegate = null;
        Thread thread = null;

        /// <summary>
        /// 完成时的回调
        /// </summary>
        /// <param name="request"></param>
        public delegate void RequestDelegate(XJNetworkRequest request, string result);

        public XJNetworkRequest(string URL,string method)
        {
            this.InitRequest(URL,method);
        }

        public XJNetworkRequest(string URL)
        {
            this.InitRequest(URL);
        }

        private void InitRequest(string URL)
        {
            this.InitRequest(URL, "GET");
        }

        private void InitRequest(string URL, string method)
        {
            this.URL = URL;
            this.method = method;
        }

        public void Start()
        {
            this.thread = new Thread(new ThreadStart(RequestAction));
            thread.IsBackground = true;
            thread.Start();
        }

        public void Stop()
        {
            this.thread.Abort();
            this.thread = null;
        }

        private void RequestAction()
        {
            this.request = (HttpWebRequest)WebRequest.Create(URL);
            this.request.Timeout = this.timeOut;
            this.request.Headers.Set("Pragma", "no-cache");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamReceive = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(streamReceive, this.encoding);
            string result = streamReader.ReadToEnd();
            if (this.requestDelegate != null)
            {
                this.requestDelegate(this, result);
            }
            this.request = null;
        }
    }
}
